package cn.conac.as.gateway.app.service;

import java.util.*;

import javax.annotation.PostConstruct;

import cn.conac.as.framework.utils.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.conac.as.gateway.app.entity.BdtLawClsIdxEntity;
import cn.conac.as.gateway.app.entity.BdtLawContentEntity;
import cn.conac.as.gateway.app.vo.BdtLawSrhVo;
import cn.conac.as.gateway.base.BaseService;

/**
 * 北大法宝接口用Service
 * @author wangmeng
 * @version 1.0
 */
@Service
public class AppLawJobService extends BaseService {

	/**
     * AppLawService(北大法宝接口用Service)
     */
    @Autowired
    private AppLawService appLawService;

	/**
     * AppLawDBService(本地数据库操作用Service)
     */
    @Autowired
    private AppLawDBService appLawDBService;

	/**
	 * 定时任务每日更新数据最大量
	 */
	@Value("${remote.pkulaw.library}")
	private String pkulawLibrary;

	/**
	 * 定时任务每日更新数据最大量
	 */
	@Value("${remote.pkulaw.pageSize}")
	private String pkulawPageSize;

    /**
     * ServiceUrl
     */
    private String serviceUrl;

    /**
     * 控制台日志
     */
    private Logger logger = Logger.getLogger(AppLawJobService.class.getName());

    public AppLawJobService() {
    }

    public AppLawJobService(String serviceUrl) {
        this.serviceUrl = serviceUrl.startsWith("http") ? serviceUrl : "http://" + serviceUrl;
    }

    /**
     * The RestTemplate works because it uses a custom request-factory that uses
     * Ribbon to look-up the service to use. This method simply exists to show
     * this.
     */
    @PostConstruct
    public void demoOnly() {
        // Can't do this in the constructor because the RestTemplate injection
        // happens afterwards.
        logger.warn("The RestTemplate request factory is " + restTemplate.getRequestFactory());
    }

    /**
     * 定时任务
     * <p>
     * 每日定时获取法律法规当日最新数据，并更新到本地DB
     * </p>
     */
    public void getDataFromRemote() {

    	// 定时任务开始
		int cnt = 0;
    	Date startDate = new Date();
		String startDateStr = DateUtils.formatDateTime(startDate);
    	logger.info("定时任务：getDataFromRemote 开始：" + startDateStr);

		// 调用数据更新接口
		BdtLawSrhVo blsVo = new BdtLawSrhVo();
		blsVo.setUpdateTime(DateUtils.getDateAfter(startDateStr,-1));// 获取前一天的数据
		blsVo.setLibrary(this.pkulawLibrary);//数据库标识
		blsVo.setPageSize(this.pkulawPageSize);//更新数据最大量
		JSONObject ssgxJsonObj = appLawService.shuJuGengXin(blsVo);

		// 当天没有要更新的数据
		if("0".equals(ssgxJsonObj.getJSONObject("Data").getString("RecordCount"))){
			logger.info("定时任务：getDataFromRemote 结束：" + DateUtils.formatDateTime(new Date()) + "，今天没有更新数据!");
			return;
		}

		JSONArray jArray = ssgxJsonObj.getJSONObject("Data").getJSONArray("Collection");
		if(jArray!=null && jArray.size()>0){
			for(int i=0; i<jArray.size(); i++){

				JSONObject jObject = jArray.getJSONObject(i);

				try{
					// 调用数据查询接口
					// blsVo.setModelTitle("十二届全国人大常委会立法规划(共102件)");
					// blsVo.setLibrary("CHL");
					blsVo.setModelGid(jObject.getString("Gid"));// 数据库标志
					blsVo.setLibrary(jObject.getString("Lib"));// 唯一标志
					JSONObject ssxxJsonObj = appLawService.shuJuChaXun(blsVo);

					JSONArray jsonArray = ssxxJsonObj.getJSONObject("Data").getJSONArray("Collection");
					if(jsonArray == null || jsonArray.size() == 0){
						continue;
					}
					JSONObject jsonObject = jsonArray.getJSONObject(0);

					// 调用数据检索接口
					blsVo.setTitle(jsonObject.getString("Title"));// 法规标题
					blsVo.setDocumentNo(jsonObject.getString("DocumentNO"));// 发文字号
					JSONObject ssjsJsonObj = appLawService.shuJuJianSuo(blsVo);

					// 如果未查到数据【没有找到此篇法规】，则不留存
					String fullText = ssjsJsonObj.getString("Data");
					if("没有找到此篇法规".equals(StringUtils.trim(fullText))){
						continue;
					}

					// ---- 数据库操作 ----
					// 检索本地DB，获取JSON数据
					BdtLawClsIdxEntity srchEntity = new BdtLawClsIdxEntity();
					srchEntity.setTitle(StringUtils.removeHtmlfromTitle(jsonObject.getString("Title")));
					srchEntity.setDocumentNo(StringUtils.insteadWithNone(jsonObject.getString("DocumentNO")));
					srchEntity.setIssueDate(StringUtils.insteadWithNone(jsonObject.getString("IssueDate")));
					JSONObject checkRtl = appLawDBService.findBdtLawClsIdxByTitleAndDocNoAndIssueDate(srchEntity);

					// 如果本地存在该条数据（同样标题、发文字号、发布日期），则更新法律法规索引表
					BdtLawClsIdxEntity blciEntity = new BdtLawClsIdxEntity();
					if(ResultPojo.CODE_SUCCESS.equals(checkRtl.getString("code"))){

						blciEntity = JSONObject.toJavaObject(checkRtl.getJSONObject("result"), BdtLawClsIdxEntity.class);

					// 如果不存在该条数据，则新建法律法规索引表
					} else {
						String id = IdGen.uuid();

						blciEntity.setId(id);

						// 追加本地DB--法律法规内容表
						BdtLawContentEntity blcEntity = new BdtLawContentEntity();
						blcEntity.setId(id);
						blcEntity.setTitle(jsonObject.getString("Title"));// 法规标题
						blcEntity.setFullText(StringUtils.dealWithFullText(fullText));// 全文
						blcEntity.setRatifyDepartment(FastJsonUtil.getJSONValue(jsonObject.getJSONObject("RatifyDepartment")));// 批准部门
						blcEntity.setRatifyDate(jsonObject.getString("RatifyDate"));// 批准日期
						appLawDBService.savOrUpdBdtLawContent(blcEntity);
					}

					// 更新或追加本地DB--法律法规索引表
					blciEntity.setTitle(jsonObject.getString("Title"));// 法规标题
					blciEntity.setDocumentNo(StringUtils.insteadWithNone(jsonObject.getString("DocumentNO")));// 发文字号
					blciEntity.setIssueDepartment(FastJsonUtil.getJSONValue(jsonObject.getJSONObject("IssueDepartment")));// 发布部门
					blciEntity.setIssueDate(StringUtils.insteadWithNone(jsonObject.getString("IssueDate")));// 发布日期
					blciEntity.setEffectivenessDic(FastJsonUtil.getJSONKey(jsonObject.getJSONObject("EffectivenessDic")).substring(0,4));// 效力级别CD
					blciEntity.setEffectiveness(appLawDBService.findByClsCode12("EffectivenessDic",blciEntity.getEffectivenessDic()).getJSONObject("result").getString("clsName2"));// 效力级别NAME
					blciEntity.setCategory(FastJsonUtil.getJSONValue(jsonObject.getJSONObject("Category")));// 法规类别
					blciEntity.setTimelinessDic(FastJsonUtil.getJSONKey(jsonObject.getJSONObject("TimelinessDic")));// 时效性CD
					blciEntity.setTimeliness(appLawDBService.findByClsCode12("TimelinessDic",blciEntity.getTimelinessDic()).getJSONObject("result").getString("clsName2"));// 时效性NAME
					blciEntity.setImplementDate(jsonObject.getString("ImplementDate"));// 实施日期
					blciEntity.setRevisedBasis(jsonObject.getString("RevisedBasis"));// 修改依据
					blciEntity.setPartialFailureBasis(jsonObject.getString("PartialFailureBasis"));// 部分失效依据
					blciEntity.setFailureBasis(jsonObject.getString("FailureBasis"));// 失效依据
					blciEntity.setLibrary(blsVo.getLibrary());// 数据库标识
					blciEntity.setGid(blsVo.getModelGid());// 唯一标识
					appLawDBService.savOrUpdBdtLawClsIdx(blciEntity);

					cnt++;

				} catch (Exception e){
						e.printStackTrace();
						//logger.info(e);
				}
			}
		}
    	// 定时任务结束
    	logger.info("定时任务：getDataFromRemote 结束：" + DateUtils.formatDateTime(new Date()) + "，共更新数据 " + cnt + "条");
    }

}
